package com.getpebble.android.common.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ObjectUtil;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.model.PblDataModel.Column;
import com.getpebble.android.common.model.PblDataModel.Column.Type;
import java.util.ArrayList;
import java.util.List;

public class PblAndroidAppModel extends PblDataModel {
    private static final String[] ALL_COLUMNS = new String[]{"_id", "package_name", "app_name", "app_version", "chosen", "allowed", "notification_count", "last_notified_time"};
    private static final Uri TABLE_URI = PblContentProviderUtil.getTableUri("android_apps");
    private static final String TAG = PblAndroidAppModel.class.getSimpleName();

    public static class Record {
        public final boolean allowed;
        public final String appName;
        public final String appVersion;
        public final boolean chosen;
        public final long lastNotifiedTimeMillis;
        public final int notificationCount;
        public final String packageName;

        public Record(String packageName, String appName, String appVersion, boolean chosen, boolean allowed, int notificationCount, long lastNotifiedTimeMillis) {
            this.packageName = packageName;
            this.appName = appName;
            this.appVersion = appVersion;
            this.chosen = chosen;
            this.allowed = allowed;
            this.notificationCount = notificationCount;
            this.lastNotifiedTimeMillis = lastNotifiedTimeMillis;
        }

        public Bitmap getIcon() {
            Bitmap bitmap = null;
            try {
                Drawable icon = PebbleApplication.getAppContext().getPackageManager().getApplicationIcon(this.packageName);
                if (icon instanceof BitmapDrawable) {
                    int h = (int) PebbleApplication.getAppContext().getResources().getDimension(R.dimen.android_app_view_icon_wh);
                    bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) icon).getBitmap(), h, h, true);
                }
            } catch (NameNotFoundException e) {
                Trace.error(PblAndroidAppModel.TAG, "Application icon could not be found.");
            } catch (OutOfMemoryError e2) {
                Trace.warning(PblAndroidAppModel.TAG, "Out of memory getting application icon");
            }
            return bitmap;
        }

        public String toString() {
            return "AndroidAppRecord{packageName=" + this.packageName + ", appName='" + this.appName + '\'' + ", appVersion=" + this.appVersion + ", chosen='" + this.chosen + '\'' + ", allowed='" + this.allowed + '\'' + ", notificationCount='" + this.notificationCount + '\'' + ", lastNotifiedTimeMillis='" + this.lastNotifiedTimeMillis + '\'' + '}';
        }
    }

    public PblAndroidAppModel() throws IllegalArgumentException {
        super("android_apps");
        Column packageCol = new Column(Type.STRING, "package_name");
        packageCol.setUnique(true);
        addColumn(packageCol);
        addColumn(new Column(Type.STRING, "app_name"));
        addColumn(new Column(Type.STRING, "app_version"));
        addColumn(new Column(Type.STRING, "chosen"));
        addColumn(new Column(Type.INTEGER, "allowed"));
        addColumn(new Column(Type.INTEGER, "notification_count"));
        addColumn(new Column(Type.TIMESTAMP, "last_notified_time"));
    }

    private static ContentValues getContentValues(Record record) {
        int i;
        int i2 = 1;
        ContentValues cv = new ContentValues();
        cv.put("package_name", record.packageName);
        cv.put("app_name", record.appName);
        cv.put("app_version", record.appVersion);
        String str = "chosen";
        if (record.chosen) {
            i = 1;
        } else {
            i = 0;
        }
        cv.put(str, Integer.valueOf(i));
        String str2 = "allowed";
        if (!record.allowed) {
            i2 = 0;
        }
        cv.put(str2, Integer.valueOf(i2));
        cv.put("notification_count", Integer.valueOf(0));
        cv.put("last_notified_time", Integer.valueOf(0));
        return cv;
    }

    public static Record getRecordFromCursor(Cursor cursor) {
        boolean z = false;
        String string = cursor.getString(cursor.getColumnIndex("package_name"));
        String string2 = cursor.getString(cursor.getColumnIndex("app_name"));
        String string3 = cursor.getString(cursor.getColumnIndex("app_version"));
        boolean z2 = cursor.getInt(cursor.getColumnIndex("chosen")) == 1;
        if (cursor.getInt(cursor.getColumnIndex("allowed")) == 1) {
            z = true;
        }
        return new Record(string, string2, string3, z2, z, cursor.getInt(cursor.getColumnIndex("notification_count")), cursor.getLong(cursor.getColumnIndex("last_notified_time")));
    }

    public static List<String> getAllPackageRecords(ContentResolver contentResolver) {
        List<String> records = new ArrayList();
        Cursor cursor = contentResolver.query(TABLE_URI, ALL_COLUMNS, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                records.add(getRecordFromCursor(cursor).packageName);
            }
            cursor.close();
        }
        return records;
    }

    public static Record getAppRecord(String packageName, ContentResolver contentResolver) {
        if (packageName == null) {
            return null;
        }
        String selection = "package_name = ?";
        Record record = null;
        ContentResolver contentResolver2 = contentResolver;
        Cursor cursor = contentResolver2.query(TABLE_URI, ALL_COLUMNS, "package_name = ?", new String[]{packageName}, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                record = getRecordFromCursor(cursor);
            }
            cursor.close();
        }
        return record;
    }

    public static CursorLoader getCursorLoader(Context context) {
        String sort = "app_name ASC";
        return new CursorLoader(context, TABLE_URI, ALL_COLUMNS, null, null, "app_name ASC");
    }

    public static synchronized boolean insertOrUpdate(ContentResolver contentResolver, Record record) throws IllegalArgumentException {
        boolean z = true;
        synchronized (PblAndroidAppModel.class) {
            if (contentResolver == null) {
                throw new IllegalArgumentException("Cannot insert record with null content resolver");
            }
            Record existingRecord = getAppRecord(record.packageName, contentResolver);
            if (existingRecord != null) {
                String selection = "package_name = ?";
                String[] args = new String[]{record.packageName};
                ContentValues values = new ContentValues();
                values.put("app_name", record.appName);
                values.put("app_version", record.appVersion);
                contentResolver.update(TABLE_URI, values, "package_name = ?", args);
                if (ObjectUtil.nullCheckEquals(existingRecord.appVersion, record.appVersion)) {
                    z = false;
                }
            } else {
                Trace.debug(TAG, "Inserting notification record: " + record.toString());
                contentResolver.insert(TABLE_URI, getContentValues(record));
            }
        }
        return z;
    }

    public static synchronized void delete(ContentResolver contentResolver, String packageName) throws IllegalArgumentException {
        synchronized (PblAndroidAppModel.class) {
            if (contentResolver == null) {
                throw new IllegalArgumentException("Cannot insert record with null content resolver");
            }
            String[] selectionArgs = new String[]{packageName};
            contentResolver.delete(TABLE_URI, "package_name = ?", selectionArgs);
        }
    }

    public static void setChosen(String packageName, boolean chosen, ContentResolver contentResolver) {
        String selection = "package_name = ?";
        String[] args = new String[]{packageName};
        ContentValues values = new ContentValues();
        values.put("chosen", Boolean.valueOf(chosen));
        contentResolver.update(TABLE_URI, values, "package_name = ?", args);
    }

    public static void setAllowed(String packageName, boolean allowed, ContentResolver contentResolver) {
        String selection = "package_name = ?";
        String[] args = new String[]{packageName};
        ContentValues values = new ContentValues();
        values.put("allowed", Boolean.valueOf(allowed));
        contentResolver.update(TABLE_URI, values, "package_name = ?", args);
    }

    public static void setAllAppsChosen(boolean chosen, ContentResolver contentResolver) {
        ContentValues values = new ContentValues();
        values.put("chosen", Boolean.valueOf(chosen));
        String selection = "allowed = ?";
        contentResolver.update(TABLE_URI, values, "allowed = ?", new String[]{"1"});
    }
}
